package com.ruoyi.workbench.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.DeptConstants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.workbench.domain.WbVisitLogStatistics;
import com.ruoyi.workbench.domain.WbVisitLogStatisticsOne;
import com.ruoyi.workbench.domain.WbWholeUnitNew;
import com.ruoyi.workbench.mapper.WbVisitLogMapper;
import com.ruoyi.workbench.service.IWbVisitLogStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 上报统计Service业务层处理
 *
 * @author hanjiafeng
 * @date 2021-02-26
 */
@Service
@Slf4j
public class WbVisitLogStatisticsServiceImpl implements IWbVisitLogStatisticsService {
    private final ISysDeptService sysDeptService;
    private final WbVisitLogMapper wbVisitLogMapper;

    public WbVisitLogStatisticsServiceImpl(WbVisitLogMapper wbVisitLogMapper, ISysDeptService sysDeptService) {
        this.wbVisitLogMapper = wbVisitLogMapper;
        this.sysDeptService = sysDeptService;
    }

    /**
     * 查询上报统计列表
     *
     * @param wbWholeUnitNew wbWholeUnitNew
     * @return 上报统计
     */
    @Override
    @Deprecated
    @DataScope(deptAlias = "sd", userAlias = "su")
    public List<WbVisitLogStatistics> selectWbVisitLogStatisticsList(WbWholeUnitNew wbWholeUnitNew, Integer period, String startTime, String endTime, String... types) {

        SysUser sysUser = ShiroUtils.getSysUser();
        SysDept sysDept = sysDeptService.selectDeptById(sysUser.getDeptId());
        int level;
        //如果用户在根目录下，则用户等级为2，否则为逗号数量加3
        if (sysDept.getDeptId().equals(DeptConstants.ROOT_DEPT_ID)) {
            level = DeptConstants.UNIT_LEVEL_2;
        } else {
            level = sysDept.getLevel();
        }
        switch (level) {
            case 2:
                break;
            case 3:
                if (Objects.isNull(wbWholeUnitNew.getUnit3())) {
                    wbWholeUnitNew.setUnit3(new SysDept());
                }
                break;
            case 4:
                if (Objects.isNull(wbWholeUnitNew.getUnit4())) {
                    wbWholeUnitNew.setUnit4(new SysDept());
                }
                break;
            case 5:
                if (Objects.isNull(wbWholeUnitNew.getUnit5())) {
                    wbWholeUnitNew.setUnit5(new SysDept());
                }
                break;
            default:
                throw new IllegalArgumentException("用户等级异常");
        }
        if (wbWholeUnitNew.getUnit5() != null) {
            sysDept = wbWholeUnitNew.getUnit5();
        } else if (wbWholeUnitNew.getUnit4() != null) {
            sysDept = wbWholeUnitNew.getUnit4();
        } else if (wbWholeUnitNew.getUnit3() != null) {
            sysDept = wbWholeUnitNew.getUnit3();
        }
        List<WbVisitLogStatistics> wbVisitLogStatisticsList = new ArrayList<>();
        List<WbVisitLogStatisticsOne> increaseList = wbVisitLogMapper.selectWbVisitLogStatisticsOneNew(wbWholeUnitNew, period, startTime, endTime, types);
        //添加新增合计
        AtomicLong increaseTotalCountAtomicLong = new AtomicLong(0);
        AtomicLong ownNetUserTotalCountAtomicLong = new AtomicLong(0);
        AtomicLong otherNetUserTotalCountAtomicLong = new AtomicLong(0);
        AtomicLong potentialUserTotalCountAtomicLong = new AtomicLong(0);
        AtomicLong transformedTotalCountAtomicLong = new AtomicLong(0);
        NumberFormat numberInstance = NumberFormat.getNumberInstance();
        numberInstance.setMaximumFractionDigits(2);
        List<SysDept> deptList = sysDeptService.selectChildrenDeptFilterByTypes(sysDept, "1", "2", "3");
        //遍历新增
        increaseList.forEach(wbVisitLogStatisticsOne -> {
            WbVisitLogStatistics wbVisitLogStatistics = new WbVisitLogStatistics(period);
            //移除已经添加的部门
            for (int i = deptList.size() - 1; i >= 0; i--) {
                if (deptList.get(i).getDeptId().equals(wbVisitLogStatisticsOne.getUnitId())) {
                    deptList.remove(i);
                }
            }
            //设置负责人
            wbVisitLogStatistics.setPrincipal(wbVisitLogStatisticsOne.getPrincipal());
            //设置单元
            wbVisitLogStatistics.setUnitName(wbVisitLogStatisticsOne.getUnitName());
            //设置增加数量
            Long increaseCount = wbVisitLogStatisticsOne.getIncreaseCount();
            Long ownNetUser = wbVisitLogStatisticsOne.getOwnNetUserCount();
            Long otherNetUser = wbVisitLogStatisticsOne.getOtherNetUserCount();
            Long potentialUser = wbVisitLogStatisticsOne.getPotentialUserCount();
            Long transformed = wbVisitLogStatisticsOne.getTransformedCount();
            increaseTotalCountAtomicLong.getAndAdd(increaseCount);
            ownNetUserTotalCountAtomicLong.getAndAdd(ownNetUser);
            otherNetUserTotalCountAtomicLong.getAndAdd(otherNetUser);
            potentialUserTotalCountAtomicLong.getAndAdd(potentialUser);
            transformedTotalCountAtomicLong.getAndAdd(transformed);
            //设置每个统计的数量
            wbVisitLogStatistics.setIncreaseCount(increaseCount);
            wbVisitLogStatistics.setOwnNetUserCount(ownNetUser);
            wbVisitLogStatistics.setOtherNetUserCount(otherNetUser);
            wbVisitLogStatistics.setPotentialUserCount(potentialUser);
            wbVisitLogStatistics.setTransformedCount(transformed);
            String transformedRate = numberInstance.format((double) transformed / increaseCount) + "%";
            wbVisitLogStatistics.setTransformedRate(transformedRate);
            wbVisitLogStatisticsList.add(wbVisitLogStatistics);
        });
        //合计
        WbVisitLogStatistics totalWbVisitLogStatistics = new WbVisitLogStatistics(period);
        totalWbVisitLogStatistics.setUnitName("合计");
        totalWbVisitLogStatistics.setIncreaseCount(increaseTotalCountAtomicLong.get());
        totalWbVisitLogStatistics.setOwnNetUserCount(ownNetUserTotalCountAtomicLong.get());
        totalWbVisitLogStatistics.setOtherNetUserCount(otherNetUserTotalCountAtomicLong.get());
        totalWbVisitLogStatistics.setPotentialUserCount(potentialUserTotalCountAtomicLong.get());
        totalWbVisitLogStatistics.setTransformedCount(transformedTotalCountAtomicLong.get());
        String transformedRate = "0%";
        if (increaseTotalCountAtomicLong.get() != 0) {
            transformedRate = numberInstance.format((double) transformedTotalCountAtomicLong.get() / increaseTotalCountAtomicLong.get()) + "%";
        }
        totalWbVisitLogStatistics.setTransformedRate(transformedRate);
        wbVisitLogStatisticsList.add(0, totalWbVisitLogStatistics);
        deptList.forEach(tempDept -> {
            WbVisitLogStatistics wbVisitLogStatistics = new WbVisitLogStatistics(period);
            wbVisitLogStatistics.setUnitName(tempDept.getDeptName());
            wbVisitLogStatistics.setPrincipal(tempDept.getLeader());
            wbVisitLogStatistics.setTransformedRate("0%");
            wbVisitLogStatisticsList.add(wbVisitLogStatistics);
        });
        return wbVisitLogStatisticsList;
    }

    @Override
    @DataScope(deptAlias = "sd", userAlias = "su")
    public List<WbVisitLogStatistics> selectWbVisitLogStatisticsList(WbWholeUnitNew wbWholeUnitNew, Byte type) {

        /*SysUser sysUser = ShiroUtils.getSysUser();
        SysDept sysDept = sysDeptService.selectDeptById(sysUser.getDeptId());
        Byte level = sysDept.getLevel();
        switch (level) {
            case 2:
                break;
            case 3:
                if (Objects.isNull(wbWholeUnitNew.getUnit3())) {
                    wbWholeUnitNew.setUnit3(new SysDept());
                }
                break;
            case 4:
                if (Objects.isNull(wbWholeUnitNew.getUnit4())) {
                    wbWholeUnitNew.setUnit4(new SysDept());
                }
                break;
            case 5:
                if (Objects.isNull(wbWholeUnitNew.getUnit5())) {
                    wbWholeUnitNew.setUnit5(new SysDept());
                }
                break;
            default:
                throw new IllegalArgumentException("用户等级异常");
        }
        if (wbWholeUnitNew.getUnit5() != null) {
            sysDept = wbWholeUnitNew.getUnit5();
        } else if (wbWholeUnitNew.getUnit4() != null) {
            sysDept = wbWholeUnitNew.getUnit4();
        } else if (wbWholeUnitNew.getUnit3() != null) {
            sysDept = wbWholeUnitNew.getUnit3();
        }
        List<WbVisitLogStatistics> wbVisitLogStatisticsList = new ArrayList<>();
        List<WbVisitLogStatisticsOne> totalList = wbVisitLogMapper.selectWbVisitLogStatisticsOneNew(wbWholeUnitNew, null, type);
        List<WbVisitLogStatisticsOne> todayList = wbVisitLogMapper.selectWbVisitLogStatisticsOneNew(wbWholeUnitNew, 0, type);
        List<WbVisitLogStatisticsOne> weekList = wbVisitLogMapper.selectWbVisitLogStatisticsOneNew(wbWholeUnitNew, 6, type);
        List<WbVisitLogStatisticsOne> monthList = wbVisitLogMapper.selectWbVisitLogStatisticsOneNew(wbWholeUnitNew, 29, type);
        List<WbVisitLogStatisticsOne> quarterList = wbVisitLogMapper.selectWbVisitLogStatisticsOneNew(wbWholeUnitNew, 89, type);
        sysDept.setType(type);
        List<SysDept> deptList = sysDeptService.selectChildrenDeptFilterByTypes(sysDept, "1", "2", "3");
        AtomicLong allTotalCount = new AtomicLong();
        AtomicLong allTodayIncrease = new AtomicLong();
        AtomicLong allWeekIncrease = new AtomicLong();
        AtomicLong allMonthIncrease = new AtomicLong();
        AtomicLong allQuarterIncrease = new AtomicLong();
        totalList.forEach(wbVisitLogStatisticsOne -> {
            WbVisitLogStatistics wbVisitLogStatistics = new WbVisitLogStatistics();
            long unitId = wbVisitLogStatisticsOne.getUnitId();
            //移除已经添加的部门
            for (int i = deptList.size() - 1; i >= 0; i--) {
                if (deptList.get(i).getDeptId() == wbVisitLogStatisticsOne.getUnitId()) {
                    deptList.remove(i);
                }
            }
            wbVisitLogStatistics.setPrincipal(wbVisitLogStatisticsOne.getPrincipal());
            wbVisitLogStatistics.setUnitName(wbVisitLogStatisticsOne.getUnitName());
            //设置总数
            wbVisitLogStatistics.setTotalCount(wbVisitLogStatisticsOne.getCount());
            allTotalCount.addAndGet(wbVisitLogStatistics.getTotalCount());
            //设置今日新增
            todayList.forEach(today -> {
                long todayUnitId = today.getUnitId();
                if (unitId == todayUnitId) {
                    wbVisitLogStatistics.setTodayIncrease(today.getCount());
                    allTodayIncrease.addAndGet(today.getCount());
                }
            });
            //设置本周新增
            weekList.forEach(week -> {
                long weekUnitId = week.getUnitId();
                if (unitId == weekUnitId) {
                    wbVisitLogStatistics.setWeekIncrease(week.getCount());
                    allWeekIncrease.addAndGet(week.getCount());
                }
            });
            //设置本月新增
            monthList.forEach(month -> {
                long monthUnitId = month.getUnitId();
                if (unitId == monthUnitId) {
                    wbVisitLogStatistics.setMonthIncrease(month.getCount());
                    allMonthIncrease.addAndGet(month.getCount());
                }
            });
            //设置本季度新增
            quarterList.forEach(quarter -> {
                long quarterUnitId = quarter.getUnitId();
                if (unitId == quarterUnitId) {
                    wbVisitLogStatistics.setQuarterIncrease(quarter.getCount());
                    allQuarterIncrease.addAndGet(quarter.getCount());
                }
            });
            wbVisitLogStatisticsList.add(wbVisitLogStatistics);
        });

        deptList.forEach(tempDept -> {
            WbVisitLogStatistics wbVisitLogStatistics = new WbVisitLogStatistics();
            wbVisitLogStatistics.setUnitName(tempDept.getDeptName());
            wbVisitLogStatistics.setPrincipal(tempDept.getLeader());
            wbVisitLogStatisticsList.add(wbVisitLogStatistics);
        });

        WbVisitLogStatistics totalStatistics = new WbVisitLogStatistics();
        totalStatistics.setUnitName("合计");
        totalStatistics.setTotalCount(allTotalCount.get());
        totalStatistics.setTodayIncrease(allTodayIncrease.get());
        totalStatistics.setWeekIncrease(allWeekIncrease.get());
        totalStatistics.setMonthIncrease(allMonthIncrease.get());
        totalStatistics.setQuarterIncrease(allQuarterIncrease.get());

        wbVisitLogStatisticsList.add(0, totalStatistics);
        return wbVisitLogStatisticsList;*/
        return null;
    }
}
